package controllers

import (
	"net/http"
	"strconv"

	"WHY_GIN/service"
	"github.com/gin-gonic/gin"
)

// ForecastController 预测控制器
type ForecastController struct {
	forecastService *service.DogeUSDTForecastService
}

// NewForecastController 创建预测控制器
func NewForecastController(forecastService *service.DogeUSDTForecastService) *ForecastController {
	return &ForecastController{
		forecastService: forecastService,
	}
}

// GetDogeUSDTScore 获取DOGE/USDT单边上涨评分
// @Summary 获取DOGE/USDT单边上涨评分
// @Description 基于技术指标计算DOGE/USDT的单边上涨评分
// @Tags 预测分析
// @Accept json
// @Produce json
// @Param update query bool false "是否更新数据" default(false)
// @Success 200 {object} service.ForecastScore "评分结果"
// @Failure 400 {object} map[string]interface{} "请求参数错误"
// @Failure 500 {object} map[string]interface{} "服务器内部错误"
// @Router /forecast/doge-usdt/score [get]
func (fc *ForecastController) GetDogeUSDTScore(c *gin.Context) {
	// 检查是否需要更新数据
	updateParam := c.Query("update")
	if updateParam != "" {
		if update, err := strconv.ParseBool(updateParam); err == nil && update {
			if err := fc.forecastService.UpdateData(); err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{
					"error":   "更新数据失败",
					"message": err.Error(),
				})
				return
			}
		}
	}

	// 检查数据是否准备就绪
	if !fc.forecastService.IsDataReady() {
		c.JSON(http.StatusBadRequest, gin.H{
			"error":   "数据未准备就绪",
			"message": "需要至少50根K线数据进行分析",
		})
		return
	}

	// 计算评分
	score, err := fc.forecastService.CalculateScore()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error":   "计算评分失败",
			"message": err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, score)
}

// GetDogeUSDTStatus 获取DOGE/USDT预测服务状态
// @Summary 获取预测服务状态
// @Description 获取DOGE/USDT预测服务的当前状态信息
// @Tags 预测分析
// @Accept json
// @Produce json
// @Success 200 {object} map[string]interface{} "状态信息"
// @Router /forecast/doge-usdt/status [get]
func (fc *ForecastController) GetDogeUSDTStatus(c *gin.Context) {
	status := gin.H{
		"symbol":         fc.forecastService.GetSymbol(),
		"data_ready":     fc.forecastService.IsDataReady(),
		"last_update":    fc.forecastService.GetLastUpdateTime(),
		"service_status": "运行中",
		"description":    "DOGE/USDT单边上涨评分系统 - 实验性功能",
	}

	c.JSON(http.StatusOK, status)
}

// InitializeDogeUSDTData 初始化DOGE/USDT数据
// @Summary 初始化预测数据
// @Description 初始化DOGE/USDT的历史K线数据
// @Tags 预测分析
// @Accept json
// @Produce json
// @Success 200 {object} map[string]interface{} "初始化结果"
// @Failure 500 {object} map[string]interface{} "服务器内部错误"
// @Router /forecast/doge-usdt/initialize [post]
func (fc *ForecastController) InitializeDogeUSDTData(c *gin.Context) {
	err := fc.forecastService.InitializeData()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error":   "初始化数据失败",
			"message": err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"message":     "数据初始化成功",
		"symbol":      fc.forecastService.GetSymbol(),
		"data_ready":  fc.forecastService.IsDataReady(),
		"last_update": fc.forecastService.GetLastUpdateTime(),
	})
}

// GetIndicatorsInfo 获取技术指标说明
// @Summary 获取技术指标说明
// @Description 获取评分系统中各技术指标的详细说明
// @Tags 预测分析
// @Accept json
// @Produce json
// @Success 200 {object} map[string]interface{} "指标说明"
// @Router /forecast/indicators/info [get]
func (fc *ForecastController) GetIndicatorsInfo(c *gin.Context) {
	indicators := gin.H{
		"total_score": 100,
		"indicators": []gin.H{
			{
				"name":        "MA多头排列",
				"weight":      20,
				"description": "趋势性判断核心指标。多头排列通常指短期均线在长期均线之上，如5MA > 10MA > 20MA > 50MA等，表明上涨趋势明确。",
			},
			{
				"name":        "RSI > 60",
				"weight":      15,
				"description": "中强动能区域。RSI（相对强弱指数）高于60通常表示资产处于较强的买入势头，但尚未超买（一般超买阈值为70）。",
			},
			{
				"name":        "RSI连续上升3日",
				"weight":      15,
				"description": "动能延续性体现。RSI连续上升表明上涨动力在持续增强。",
			},
			{
				"name":        "成交量 > 1.5倍均值",
				"weight":      15,
				"description": "防止虚涨。成交量显著高于平均水平，确认价格上涨有实际交易量支撑，而非少量资金推动的假突破。",
			},
			{
				"name":        "当前价格 > 20MA",
				"weight":      10,
				"description": "短期强势表现。价格高于20日均线通常被视为短期趋势向上的信号。",
			},
			{
				"name":        "连续3根阳线",
				"weight":      5,
				"description": "短期情绪判断。连续阳线显示市场买盘强劲，情绪积极。",
			},
			{
				"name":        "突破布林带上轨",
				"weight":      10,
				"description": "强势信号初现。布林带上轨代表价格的上限，突破可能预示着强劲的上涨势头。",
			},
			{
				"name":        "连续2日收盘价 > 上轨",
				"weight":      10,
				"description": "趋势确认信号。连续两天收盘在上轨之上，确认突破的有效性，减少假信号的可能性。",
			},
		},
		"score_levels": []gin.H{
			{"range": "80-100", "recommendation": "强烈看涨 - 建议关注买入机会"},
			{"range": "60-79", "recommendation": "看涨 - 可考虑适量买入"},
			{"range": "40-59", "recommendation": "中性偏多 - 观望为主"},
			{"range": "20-39", "recommendation": "中性偏空 - 谨慎操作"},
			{"range": "0-19", "recommendation": "看空 - 建议回避"},
		},
		"notice": "此评分系统仅供实验和学习使用，不构成投资建议。请勿用于实际交易决策。",
	}

	c.JSON(http.StatusOK, indicators)
}